<!-- 完善联系人信息 -->
<template>
    <div>
        <FormProcess step="-1" :registerStatus="this.userStatus" v-if="this.userStatus.accountBinding != 2"/>
        <FormTitle title="联系人信息"/>
        <div class="form-box">
            <el-form :model="form" ref="form" :rules="rules" label-width="130px" class="demo-ruleForm edit-form-box" v-if="this.userStatus.businessAuthorizationStatus != 2">
                <el-row class="form-conent-box">
                    <el-col :span="24" class="customer-form-title"><div class="grid-content bg-purple-dark">联系人身份证上传：<i class="customer-title-i">*(身份证正反面都必须上传！)</i></div></el-col>
                    <el-col :span="24">
                        <div class="id-card-img">
                            <div class="upload-img-box">
                                <div class="img-box">
                                    <ImageZoom
                                            :width='238'
                                            :height='154'
                                            :image="form.id_front_photo_address"
                                    ></ImageZoom>
                                </div>
                                <div class="upload-btn">
                                    <UploaderImages @input="forntCartImg" uploadText="上传正面"></UploaderImages>
                                </div>
                            </div>
                            <div class="upload-img-box">
                                <div class="img-box">
                                    <ImageZoom
                                            :width='238'
                                            :height='154'
                                            :image="form.id_back_photo_address"
                                    ></ImageZoom>
                                </div>
                                <div class="upload-btn">
                                    <UploaderImages @input="bankCartImg" uploadText="上传反面"></UploaderImages>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="register-int-box approve-int-box">
                            <el-form-item label="手机号：">
                                <span>{{form.phone_number}}</span>
                            </el-form-item>
                            <el-form-item label="姓名：" prop="customer_name">
                                <el-input class="approve-int" v-model="form.customer_name" placeholder="请输入姓名"></el-input>
                            </el-form-item>
                            <el-form-item label="性别：" prop="sex">
                                <el-button type="primary" class="sex-btn" :class="{'sex-btn-active': form.sex == '男'}" @click="form.sex = '男'">男</el-button>
                                <el-button type="primary" class="sex-btn" :class="{'sex-btn-active': form.sex == '女'}" @click="form.sex = '女'">女</el-button>
                            </el-form-item>
                            <el-form-item label="身份证号：" prop="id_number">
                                <el-input class="approve-int" v-model="form.id_number" placeholder="请输入身份证号"></el-input>
                            </el-form-item>
                            <el-form-item label="电子邮箱：" prop="email">
                                <el-input class="approve-int" v-model="form.email" placeholder="请输入电子邮箱"></el-input>
                            </el-form-item>
                            <el-form-item prop="customerAddressArray" label="交易地点：" class="customer-addr">
                                <FormAddress ref="customerAddressArray" v-model="form.customerAddressArray"></FormAddress>
                                <i class="iconfont icon-xuanzedizhi"></i>
                            </el-form-item>
                            <el-form-item label="详细地址：" prop="contact_address">
                                <el-input type="textarea" v-model="form.contact_address" :rows="3" resize="none" class="approve-int" placeholder="请输入具体通讯地址"></el-input>
                            </el-form-item>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="submit-btn approve-submit-btn">
                            <el-button type="info" size="small" @click="exitApprove()">取消</el-button>
                            <el-button type="primary" size="small" @click="saveCustomer()">提交</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
            <el-form :model="form" ref="form" :rules="rules" label-width="130px" class="demo-ruleForm edit-form-box" v-if="this.userStatus.isVerified == 1 && this.userStatus.businessAuthorizationStatus == 2">
                <el-row class="form-conent-box">
                    <el-col :span="24" class="customer-form-title"><div class="grid-content bg-purple-dark">联系人身份证上传：<i class="customer-title-i">*(身份证正反面都必须上传！)</i></div></el-col>
                    <el-col :span="24">
                        <div class="id-card-img">
                            <div class="upload-img-box">
                                <div class="img-box">
                                    <ImageZoom
                                            :width='238'
                                            :height='154'
                                            :image="form.id_front_photo_address"
                                    ></ImageZoom>
                                </div>
                            </div>
                            <div class="upload-img-box">
                                <div class="img-box">
                                    <ImageZoom
                                            :width='238'
                                            :height='154'
                                            :image="form.id_back_photo_address"
                                    ></ImageZoom>
                                </div>
                            </div>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="register-int-box approve-int-box">
                            <el-form-item label="手机号：">
                                <span>{{form.phone_number}}</span>
                            </el-form-item>
                            <el-form-item label="姓名：">
                                {{form.customer_name}}
                            </el-form-item>
                            <el-form-item label="性别：">
                                <el-button type="primary" class="sex-btn" :class="{'sex-btn-active': form.sex == '男'}">男</el-button>
                                <el-button type="primary" class="sex-btn" :class="{'sex-btn-active': form.sex == '女'}">女</el-button>
                            </el-form-item>
                            <el-form-item label="身份证号：">
                                <span>{{form.id_number}}</span>
                            </el-form-item>
                            <el-form-item label="电子邮箱：">
                                {{form.email}}
                            </el-form-item>
                            <el-form-item prop="addressArray" label="交易地点：" class="customer-addr">
                                {{form.trade_location_province}}/{{form.trade_location_city}}/{{form.trade_location}}
                            </el-form-item>
                            <el-form-item label="详细地址：" prop="contact_address">
                                {{form.contact_address}}
                            </el-form-item>
                        </div>
                        <div class="go_back"><el-button type="text" @click="exitApprove()"><i class="iconfont icon-fanhui"></i> 返回上一页</el-button></div>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts">
    import { Vue, Component, Prop } from 'vue-property-decorator';
    import FormProcess from '@component/common/FormProcess.vue';
    import FormTitle from '@component/common/FormTitle.vue';
    import FormImages from '@component/common/FormImages.vue';
    import DialogInput from '@component/common/DialogInput.vue';
    import FormAddress from '@component/common/FormAddress.vue';
    import UploaderImages from '@component/common/UploaderImages.vue';
    import ImageZoom from '@component/common/ImageZoom.vue';
    import { mapState, mapMutations, mapGetters, mapActions } from 'vuex';
    import { Mutation } from 'vuex-class';
    import { checkIDHPX } from '@/util/format';
    import _ from 'lodash';

    @Component({
        components: {
            FormProcess,
            FormTitle,
            FormImages,
            DialogInput,
            FormAddress,
            UploaderImages,
            ImageZoom
        },
        computed: {
            ...mapState([
                "userStatus"
            ]),
            ...mapGetters([
                'userInfo'
            ])
        },
        methods: {
            ...mapActions([
                "getPolicy",
                "getStatus",
            ])
        }
    })
    export default class ApproveCustomer extends Vue {
        @Prop() images!: any;
        @Mutation setUser;
        form = {
            customer_name: '',
            sex: '',
            id_number: '',
            email: '',
            images: [],
            phone_number: '',
            customerAddressArray: [],
            contact_address: '',
            id_front_photo_address: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/registerImgTem/id-card-front.png',
            id_front_photo_id: '',
            id_back_photo_address: 'https://hpx-pc.oss-cn-beijing.aliyuncs.com/registerImgTem/id-card-bank.png',
            id_back_photo_id: ''
        }
        tempForm = {}
        rules = {
            customer_name: [
                {required: true, message: '请输入姓名', trigger: 'blur'}
            ],
            sex: [
                {required: true, message: '请选择性别', trigger: 'blur'}
            ],
            id_number: [
                { required: true, message: '请输入身份证号', trigger: 'blur' },
                // { validator: checkIDHPX, message: '身份证号错误', trigger: 'blur' }
                // {
                //     pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
                //     message: '身份证号错误',
                //     trigger: 'blur'
                // }
            ],
            email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
                {
                    pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
                    message: '输入的邮箱有误',
                    trigger: 'blur'
                }
            ]
            // customerAddressArray: [
            //     { required: true, message: '请选择地址', trigger: 'blur' }
            // ]
        }
        // 正面
        forntCartImg(valData: any) {
            if(valData != null && valData != undefined){
                this.form.id_front_photo_address = valData.path;
                this.form.id_front_photo_id = valData.id;
                this.idCartOcr(valData.path);
            }
        }
        // 身份证正面ocr
        idCartOcr (imageUrl: string) {
            this.$http.get(`ocr/idcard?faceOrBack=face&imageUrl=${imageUrl}`)
                .then((response) => {
                    if(response.data != null){
                        this.form.customer_name = response.data.name;
                        this.form.sex = response.data.sex;
                        this.form.id_number = response.data.id_num;
                    }
                })
        }
        // 背面
        bankCartImg (valData: any) {
            this.form.id_back_photo_address = valData.path;
            this.form.id_back_photo_id = valData.id;
        }
        saveCustomer () {
            if(!checkIDHPX(this.form.id_number) && this.form.id_number != ''){
                this.$alert('请输入正确的身份证号！','提示',{
                    confirmButtonText: '确定',
                    customClass: 'custom-message-box',
                    callback: action => {}
                })
                return;
            }
            this.$refs.form.validate(valid => {
                let customerForm = this.form;
                if(!customerForm.id_front_photo_id || customerForm.id_front_photo_id == ""){
                    this.$alert('请上传身份证正面！','提示',{
                        confirmButtonText: '确定',
                        customClass: 'custom-message-box',
                        callback: action => {}
                    })
                    return;
                }
                if(!customerForm.id_back_photo_id || customerForm.id_back_photo_id == ""){
                    this.$alert('请上传身份证背面！','提示',{
                        confirmButtonText: '确定',
                        customClass: 'custom-message-box',
                        callback: action => {}
                    })
                    return;
                }
                // if (customerForm.customerAddressArray.length < 1){
                //     this.$alert('请选择正确的地址！','提示',{
                //         confirmButtonText: '确定',
                //         customClass: 'custom-message-box',
                //         callback: action => {}
                //     })
                //     return;
                // }
                // if (customerForm.customerAddressArray)
                // console.log(customerForm.customerAddressArray.length)
                if (customerForm.customerAddressArray.length > 1){
                    if(customerForm.customerAddressArray.length == 3){
                        customerForm.trade_location_province_id = customerForm.customerAddressArray[0];
                        customerForm.trade_location_province = '';
                        customerForm.trade_location_city_id = customerForm.customerAddressArray[1];
                        customerForm.trade_location_city = '';
                        customerForm.trade_location_id = customerForm.customerAddressArray[2];
                        customerForm.trade_location = '';
                    }else if (customerForm.customerAddressArray.length == 2) {
                        customerForm.trade_location_province_id = customerForm.customerAddressArray[0];
                        customerForm.trade_location_province = '';
                        customerForm.trade_location_city_id = '';
                        customerForm.trade_location_city = '';
                        customerForm.trade_location_id = customerForm.customerAddressArray[1];
                        customerForm.trade_location = '';
                    }
                } else {
                    customerForm.trade_location_province_id = '';
                    customerForm.trade_location_province = '';
                    customerForm.trade_location_city_id = '';
                    customerForm.trade_location_city = '';
                    customerForm.trade_location_id = '';
                    customerForm.trade_location = '';
                }

                if(valid){
                    this.sendCustomer(customerForm);
                }
            })
        }
        // 发送保存联系人请求
        async sendCustomer (form) {
            // console.log(form)
            let self = this;
            this.$http.put('customers/customer',form)
                .then((response) => {
                    if(response.status == 200) {
                        this.getStatus();
                        self.getCustomer();
                        this.$confirm('联系人保存成功，请完善企业信息！','提醒',{
                            confirmButtonText: '继续',
                            cancelButtonText: '以后再说',
                            customClass: 'custom-message-box',
                        }).then(() => {
                            if(this.userStatus.agencyCertificationStatus == 0){
                                this.$router.push('/approveEnterprise');
                            }else if (this.userStatus.businessAuthorizationStatus == 0){
                                this.$router.push('/approveAgent');
                            }else if(this.userstatus.accountBinding == 0){
                                this.$router.push('/approveAccount');
                            }
                        }).catch(() => {
                            location.href="/trade.html";
                        })
                    }
                })
        }
        // 获取联系人信息
        async getCustomer () {
            this.$http.get(`customers/customer/${this.userInfo.customer_id}`)
                .then((response) => {
                    if(this.userStatus != '' && this.userStatus != null && this.userStatus.isVerified == 1){
                        this.tempForm = response.data;
                        this.platForm();
                        // 将vuex中的数据同步
                        let customer_obj = {
                            customer_name: response.data.customer_name
                        }
                        let userInfo = _.assign(this.userInfo, customer_obj)
                        this.setUser(userInfo);
                    }else {
                        this.form.phone_number = response.data.phone_number;
                    }
                })
        }
        platForm () {
            for (let key in this.tempForm) {
                this.form[key] = this.tempForm[key];
            }
            if(this.userStatus.businessAuthorizationStatus != 2 && this.tempForm.trade_location_province_id != '' && this.tempForm.trade_location_province_id != null && this.tempForm.trade_location_province_id != undefined) {
                if(this.tempForm.trade_location_province_id == 1 || this.tempForm.trade_location_province_id == 20 || this.tempForm.trade_location_province_id == 860 || this.tempForm.trade_location_province_id == 2462){
                    this.$refs.customerAddressArray.init([this.tempForm.trade_location_province_id, this.tempForm.trade_location_id]);
                }else {
                    this.$refs.customerAddressArray.init([this.tempForm.trade_location_province_id, this.tempForm.trade_location_city_id, this.tempForm.trade_location_id]);
                }
            }
        }
        // 退出认证
        exitApprove () {
            let backUrl = /back=.+$/.exec(location.hash);
            location.href = backUrl && backUrl.length == 1 ? backUrl[0].split('=')[1] : "/trade.html";
        }
        created () {
            let promise = this.getStatus();
            let self = this;
            promise.then(resolve => {
                this.getPolicy();
                this.getCustomer();
            })
        }
        mounted () {}
    }
</script>

<style lang="scss" scoped>
    .register-int-box {
        margin-top: 20px;
    }
    .submit-btn {
        margin-top: 52px;
    }
    .sex-btn {
        width: 44px;
        height: 32px;
        background: #fff;
        color: $__color-show;
        padding: 0;
        border-color: $__color-border;
    }
    .sex-btn-active {
        background: $__color-primary;
        border-color: $__color-primary;
        color: #fff;
    }
    .customer-addr {
        position: relative;
        .icon-xuanzedizhi {
            position: absolute;
            top: 2px;
            left: 280px;
            color: $__color-border;
            font-size: $__little-font-size;
        }
    }
    .go_back {
        display: flex;
        justify-content: center;
        .el-button--text {
            color: $__color-link;
        }
    }
</style>
<style lang="scss">

</style>
